<template>
   <s-card title="内置音频设置" style="width: 100%">
      <div>
         <table>
            <thead>
               <tr class="info">
                  <th width="100px">类型</th>
                  <th>文件名</th>
                  <th>播放次数</th>
                  <th></th>
               </tr>
            </thead>
            <tbody>
               <tr v-for="item in list" :key="item.AudioType">
                  <td>{{ radioTypes[item.AudioType] }}</td>
                  <td>{{ item.FileName }}</td>
                  <td>
                     <s-input
                        :inputStyle="{width:'70px'}"
                        :name="`type_${item.AudioType}`"
                        :value="item.PlayTimes"
                        @update="handleUpdate"
                        :min="1"
                        :max="99"
                        type="number"
                        @blur="handleBlur"
                        @focus="handleFocus"
                     />
                  </td>
                  <td>
                     <div>
                        <s-upload
                           @onSuccess="
                              (FileList) =>
                                 onSucessUpload(item.AudioType, FileList)
                           "
                           style="position: relative; display: inline-block"
                        >
                           <s-button style="margin-right: 16px; padding: 0 12px"
                              >上传</s-button
                           >
                        </s-upload>
                        <s-button :disabled="item.FileName===''" :type="item.PlayStatus===1?'success':'primary'" style="padding: 0 12px" :icon="item.PlayStatus===1?'icon-stop-fill':'icon-play-fill'" type="primary" @click="handlePlay(item.AudioType,item.PlayStatus)">{{item.PlayStatus===1?'停止':'播放'}}</s-button>
                     </div>
                  </td>
               </tr>
            </tbody>
         </table>
      </div>
      <template #footer>
         <s-button type="primary" @click="handleSubmit">应用</s-button>
      </template>
   </s-card>
</template>

<script lang="ts" setup>
import { SCard, SButton, Message, SUpload, SInput, SModal, SProgress } from "@/components"
import { onBeforeMount, ref, toRaw, onBeforeUnmount } from "vue"
import { getAudioInfo, setAudioInfo, audioListen } from "@/request"
import $axios from "@/request/config"
import { Timer } from "@/utils"

const radioTypes = {
   1: "RS485-1",
   2: "RS485-2",
   3: "RS485-3",
   4: "RS485-4",
   5: "RS485-5",
   0xf0: "开关量"
}
   interface Audio {
      AudioType: number;
      FileName: string;
      PlayTimes: number;
      PlayStatus: number;
   }
const list = ref<Array<Audio>>([])

const getInit = () => {
   getAudioInfo().then((data) => {
      list.value = data.AudioList
   })
}

const handleUpdate = (params: { name: string; value: number }) => {
   const AudioType = Number(params.name.split("_")[1])
   const newList = []
   list.value.forEach((item) => {
      let newItem = {}
      if (item.AudioType === AudioType) {
         newItem = {
            ...item,
            PlayTimes: Number(params.value)
         }
      } else {
         newItem = item
      }
      newList.push(newItem)
   })
   list.value = newList
}

const handleSubmit = () => {
   const isValid = list.value.every((item) => (Number(item.PlayTimes) >= 1 && Number(item.PlayTimes) <= 99))
   if (!isValid) {
      return Message.error("播放次数有误，请输入[1,99]范围内的整数")
   }
   const data = list.value.map((item) => ({
      AudioType: Number(item.AudioType),
      PlayTimes: Number(item.PlayTimes)
   }))

   setAudioInfo({
      AudioList: data
   }).then(() => {
      Message.success("设置成功")
      getInit()
   })
}

const handleBlur = () => {
   Timer.refreshAudio = setInterval(() => {
      getInit()
   }, 2000)
}

const handleFocus = () => {
   clearInterval(Timer.refreshAudio)
}
const handlePlay = (AudioType:number, PlayStatus:number) => {
   console.log({
      AudioType,
      IsPlay: PlayStatus === 1 ? 2 : 1
   })
   audioListen({
      AudioType,
      IsPlay: PlayStatus === 1 ? 2 : 1
   }).then(() => {
      getInit()
   })
}

// 获取文件
const onSucessUpload = (AudioType: number, fileList: FileList) => {
   if (!fileList[0]) {
      return Message.error("请先选择文件")
   }
   const fb = new FormData()
   fb.append(fileList[0].name, toRaw(fileList[0]))

   $axios.axios({
      method: "post",
      url: `ImportAduio.w?AudioType=${AudioType}&token=${localStorage.getItem("token")}`,
      data: fb,
      headers: { "Content-Type": "multipart/form-data" }
   }).then(data => {
      if (data) {
         Message.success("上传成功")
         getInit()
      }
   })
}

onBeforeMount(() => {
   getInit()
   Timer.refreshAudio = setInterval(() => {
      getInit()
   }, 2000)
})

onBeforeUnmount(() => {
   clearInterval(Timer.refreshAudio)
})

</script>

<style scoped lang="less">
   table {
      text-align: left;
      thead {
         background: aliceblue;
      }
      tr {
         height: 30px;
         line-height: 30px;
         td,
         th {
            padding: 2px 8px;
            border: 1px solid #eee;
         }
      }
   }
</style>
